import React, { PureComponent } from "react";
import { getConfig } from '../../../../config';
import Map from 'ol/Map';
import OlView from 'ol/View';
import LayerGroup from 'ol/layer/Group';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import proj from 'ol/proj';
import interaction from 'ol/interaction';
import SourceVector from 'ol/source/vector';
import LayerVector from 'ol/layer/vector';
import OlStyle from 'ol/style/style';
import StyleFill from 'ol/style/fill';
import StyleStroke from 'ol/style/stroke';
import StyleIcon from 'ol/style/icon';
import OlFeature from 'ol/feature';
import OlPoint from 'ol/geom/point';
import OlDraw from 'ol/interaction/draw';

const config = getConfig();
const mapKey = config.mapKey;
var map = null;
var E={};
var extentgeom={};
var selectedPoint = {};

class PickPostionOpenLayers extends React.Component {
    constructor() {
        super();
    }

    addPoint = () => {
        var _this = this.props;
        var self = this;
        if (!!E.drawInteraction) {
    		map.removeInteraction(E.drawInteraction);
    	}
    	E.drawInteraction = new OlDraw({
    		source :  new SourceVector(),
    		type : "Point",
    		style : new OlStyle({
    			fill : new StyleFill({
    				color : 'rgba(255, 228, 196, 0.5)'
    			}),
    			stroke : new StyleStroke({
    				color : 'rgba(0, 0, 0, 0.5)',
    				lineDash : [ 10, 10 ],
    				width : 2
    			}),
				image : new StyleIcon({
						src: '/pic_map.png'
					})
    		}), 
    	    geometryFunction: function(coordinates, geometry){
				var geom= new OlPoint([coordinates[0],coordinates[1]]); 
				return geom;
    	    }
    	});
    	map.addInteraction(E.drawInteraction);
    	E.drawInteraction.on('drawend', function(e) { 
    		E.drawInteraction.setActive(false);
			map.removeInteraction(E.drawInteraction);
				var geom2=e.feature.getGeometry().transform('EPSG:3857' ,'EPSG:4326');
                //alert("("+geom2.getCoordinates()[0]+","+geom2.getCoordinates()[1]+")");
                const lat = parseFloat(geom2.getCoordinates()[1].toFixed(6));
                const lng = parseFloat(geom2.getCoordinates()[0].toFixed(6));
                selectedPoint = {lat: lat,lng: lng};
                _this.setPosition(selectedPoint);
                self.showPosition({lat: geom2.getCoordinates()[1],lng: geom2.getCoordinates()[0]});
            }) 
    }
    componentDidMount() {
        this.props.onRef(this);
        //this.showPosition(selectedPoint);
    }
    layerContains = function (id){
        var layers = map.getLayers().getArray();
    	for (var i = 0; i < layers.length; i++) {
    		if (!!layers[i].getProperties()['name'] && layers[i].getProperties()['name'] == id) {
    			return layers[i];
    		}
    	}
    	return false;
    }
    showPosition=(point)=>{
        var data ={
            "type": "FeatureCollection",
            "features": [
                    {"type":"Feature",
                    "properties":{},
                    "geometry":{
                        "type":"Point",
                        "coordinates":[121.41,29.66]
                        }
                    }
                ]
            }       
            var layer =this.layerContains('poi');
            var source;
            if (!layer) {
                source = new SourceVector({
                    projection : 'EPSG:4326',
                    wrapX : false
                });
                var vector = new LayerVector({
                    name : "poi",
                    source : source,
                    style : new OlStyle({
                        fill : new StyleFill({
                            color : 'rgba(255, 228, 196, 0.5)'
                        }),
                        stroke : new StyleStroke({
                            color : '#ffcc33',
                            width : 2
                        }),
                        image : new StyleIcon({
                            src: '/pic_map.png'
                        })
                    })
                });
                map.addLayer(vector); 
            }else{ 
                source = layer.getSource();
            }
        source.clear();
        var geom= new OlPoint([point.lng,point.lat ]);
        geom=geom.transform( 'EPSG:4326','EPSG:3857'); 
        data.geometry =geom
        source.addFeature(new OlFeature(data));
    }

    render() {
        return null;
    }
}

const initCallback = () => {
    console.log("AMapUI Loaded Done")
}


export default class Maps extends PureComponent {
    constructor(props) {
        super(props);

    }

    componentDidMount() {
        map = new Map({
            layers: [new LayerGroup({
                classify: "base",
                layers: [new TileLayer({
                    title: "高德",
                    source: new XYZ({
                        crossOrigin: 'anonymous',
                        url: '/fenghuaGIS/map/{z}/{y}/{x}.png'
                    })
                })]
            })],
            projection: 'EPSG:3857',
            target: "mapcontent",
            logo: false,
            loadTilesWhileInteracting: true,
            controls: [],
            interactions: interaction.defaults({
                doubleClickZoom: false
            }),
            view: new OlView({
                center: proj.fromLonLat([121.41, 29.66]),
                zoom: 13,
                maxZoom: 18,
                minZoom: 0
            })
        });
        this.showPosition(selectedPoint);
    }

    layerContains = function (id){
        var layers = map.getLayers().getArray();
    	for (var i = 0; i < layers.length; i++) {
    		if (!!layers[i].getProperties()['name'] && layers[i].getProperties()['name'] == id) {
    			return layers[i];
    		}
    	}
    	return false;
    }
    showPosition=(point)=>{
        var data ={
            "type": "FeatureCollection",
            "features": [
                    {"type":"Feature",
                    "properties":{},
                    "geometry":{
                        "type":"Point",
                        "coordinates":[121.41,29.66]
                        }
                    }
                ]
            }       
            var layer =this.layerContains('poi');
            var source;
            if (!layer) {
                source = new SourceVector({
                    projection : 'EPSG:4326',
                    wrapX : false
                });
                var vector = new LayerVector({
                    name : "poi",
                    source : source,
                    style : new OlStyle({
                        fill : new StyleFill({
                            color : 'rgba(255, 228, 196, 0.5)'
                        }),
                        stroke : new StyleStroke({
                            color : '#ffcc33',
                            width : 2
                        }),
                        image : new StyleIcon({
                            src: '/pic_map.png'
                        })
                    })
                });
                map.addLayer(vector); 
            }else{ 
                source = layer.getSource();
            }
        source.clear();
        var geom= new OlPoint([point.lng,point.lat ]);
        geom=geom.transform( 'EPSG:4326','EPSG:3857'); 
        data.geometry =geom
        source.addFeature(new OlFeature(data));
    }

    handleSetPostion = (value) => {
        this.props.setPosition(value);
    }
    onRef = (ref) => {
        this.props.onRef(ref);
    }

    render() {
        const { originPos } = this.props;
        selectedPoint = originPos;
        //this.showPosition(originPos);
        const plugins = [
            // 'MapType',
            'Scale',
            // 'OverView',
            // 'ControlBar', // v1.1.0 新增
            {
                name: 'ToolBar',
                options: {
                    visible: true,  // 不设置该属性默认就是 true
                },
            }
        ]
        return (
            <div style={{ height: 500, width: '100%' }}>
                <div id="mapcontent" style={{ height: '100%', width: '100%' }}>
                </div>
                <PickPostionOpenLayers onRef={this.onRef} setPosition={this.handleSetPostion} originPos={originPos} />
            </div>
        );
    }
}